package ch02.sl;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Before;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

public class Test_DOM4J {
    SAXReader reader ;
    Document doc ;
    String url ="src/ch02/sl/TSupplierMapper.xml";
    @Before
    public void before(){
        try {
            reader = new SAXReader();
            doc =reader.read(url);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testDom4j() throws IOException {
        Element root =doc.getRootElement();
        System.out.println("根节点: "+root.getName());//books

        Iterator its_ele =root.elementIterator(); //得到所有的元素节点
        for (Iterator its = root.attributeIterator();its.hasNext();){
            Attribute attr= (Attribute) its.next();
            System.out.println("根节点的属性:"+ attr.getName()+":"+attr.getText());
        }

        System.out.println("\t----------子节点----------");
        while (its_ele.hasNext()){
            Element ele = (Element) its_ele.next();  // select

            //移除属性
          /*  Attribute attr = ele.attribute("id");
            ele.remove(attr);*/

            root.remove(ele);
            /*System.out.println("\t"+ ele.getName() +":"+ ele.getText());//
            ele.setText("这是我要修改的值");
            System.out.println();
            System.out.println("\t\t子节点属性");
            Iterator attrs =ele.attributeIterator();
            while (attrs.hasNext()){
                Attribute attr = (Attribute) attrs.next();
                System.out.println("\t\t"+ attr.getName()+":"+ attr.getText());
            }

            *//*Iterator its_child = ele.elementIterator();
            while (its_child.hasNext()){
                Element child_ele= (Element) its_child.next();  // title author desc
                System.out.println("\t\t"+ child_ele.getName()+":"+child_ele.getText());
            }*//*
            System.out.println("*******************************");*/
        }
        save();//写入
    }

    public void save() throws IOException {
        XMLWriter writer =new XMLWriter(new FileWriter(url));
        writer.write(doc);
        writer.close();
    }
}
